<template>
  <div class="content" v-loading="loading">
    <div class="inputLine flexBet">
      <div class="flex">
        <el-input
          :disabled="!isSortable"
          style="width: 320px"
          @input="getList"
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-select
          :disabled="!isSortable"
          @change="getList"
          style="width: 200px; margin-left: 16px"
          v-model="queryParams.semesterId"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""></el-option>

          <el-option
            v-for="(item, index) in semesterList"
            :key="index"
            :label="item.semesterName"
            :value="item.semesterId"
          ></el-option>
        </el-select>
      </div>

      <div class="flex">
        <div
          class="sort"
          v-if="isLeader && courseList.length > 0"
          @click="handelSort"
        >
          {{ isSortable ? '排序' : '保存' }}
        </div>
        <div
          class="sort"
          style="margin-left: 15px"
          v-if="isLeader && courseList.length > 0 && !isSortable"
          @click="handelcancel"
        >
          取消
        </div>
      </div>
    </div>
    <div class="tip">{{ !isSortable ? '注：可通过拖拽来调整排序' : '' }}</div>
    <draggable
      v-if="courseList.length > 0"
      :options="{ disabled: isSortable }"
      class="box"
      v-model="courseList"
      @end="onDragEnd"
      @start="dragStart"
    >
      <div
        @click="to(item)"
        class="course rela shou"
        v-for="(item, index) in courseList"
        :key="index"
      >
        <img
          :src="require(`@/assets/images/status${item.courseStatus}.png`)"
          class="coverTip absolute"
          alt=""
        />
        <img class="cover" :src="item.coursePic" alt=""/>
        <tooltip class="name" :text="item.courseName" width="216"></tooltip>
        <tooltip
          class="wname"
          :text="item.workstationName"
          width="216"
        ></tooltip>
      </div>
    </draggable>
    <div
      style="width: 100%; height: 100%"
      v-if="courseList.length == 0"
      class="flexCen flexColCenter"
    >
      <el-empty description="暂无课程~"></el-empty>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { getSchoolSemesterList } from '@/api/schoolSemester/schoolSemester'
import {
  branchDisciplineCourseList,
  branchDisciplineCourseSort
} from '@/api/disciplineGroup/disciplineGroup'

export default {
  components: { draggable },
  props: {
    activeIndex: [Number, String],
    disciplineGroupId: [Number, String],
    isLeader: Boolean
  },
  data() {
    return {
      isSortable: true,
      queryParams: {
        courseName: '',
        semesterId: ''
      },
      loading: false,
      semesterList: [],
      courseList: [],
      initList: []
    }
  },
  watch: {
    isSortable() {
      this.$emit('updateSorting', !this.isSortable)
    },
    activeIndex: {
      async handler(val) {
        if (val == 1) {
          await this.getSemesterList()
          this.getList()
        }
      },
      immediate: true
    },
    disciplineGroupId() {
      if (this.activeIndex == 1) {
        this.getList()
      }
    }
  },
  methods: {
    handelcancel() {
      this.courseList = this.initList
      this.isSortable = !this.isSortable
      this.$message({
        type: 'success',
        message: '取消排序'
      })
    },
    async handelSort() {
      // 要保存的时候
      if (!this.isSortable) {
        this.$emit('loading', true)
        try {
          let res = await branchDisciplineCourseSort({
            disciplineGroupId: this.disciplineGroupId,
            courseSort: this.courseList
              .map((item) => {
                return item.courseId
              })
              .join(',')
          })

          if (res.code == 200) {
            this.isSortable = !this.isSortable
            this.initList = this.courseList
            this.$message({
              type: 'success',
              message: '排序成功'
            })
          }
        } finally {
          this.$emit('loading', false)
        }
      } else {
        this.isSortable = !this.isSortable
      }
    },
    dragStart() {
    },
    onDragEnd() {
      console.log(this.courseList)
    },
    findNearestSemesterId(semesterArray) {
      const now = new Date()
      let matchedSemesterId = null
      let nearestSemesterId = null
      let minDiff = Infinity

      semesterArray.forEach((semester) => {
        const beginTime = new Date(semester.beginTime)
        const endTime = new Date(semester.endTime)

        // 判断当前时间是否在区间内
        if (now >= beginTime && now < endTime) {
          matchedSemesterId = semester.semesterId // 找到匹配的学期ID
          return // 直接跳出循环
        }

        // 如果不在区间内，计算与当前时间的差值，寻找最近的一个开始时间
        const diff = Math.abs(now - beginTime)
        if (diff < minDiff) {
          minDiff = diff
          nearestSemesterId = semester.semesterId
        }
      })

      // 如果找到了匹配的学期，优先返回匹配的学期ID
      return matchedSemesterId || nearestSemesterId || ' '
    },
    async getSemesterList() {
      this.$emit('loading', true)
      try {
        let res = await getSchoolSemesterList()
        this.semesterList = res.rows
        let semesterId = this.findNearestSemesterId(res.rows)
        // 将 this.queryParams.semesterId 对应的学期置顶，其余按时间倒序排列
        this.semesterList = this.semesterList.sort((a, b) => {
          // 如果 a 是目标学期，将其置顶
          if (a.semesterId + '' == semesterId + '') {
            return -1
          }
          // 如果 b 是目标学期，将其置顶
          if (b.semesterId + '' == semesterId + '') {
            return 1
          }
          // 否则按 beginTime 时间倒序排列
          return new Date(b.beginTime) - new Date(a.beginTime)
        })
      } finally {
        this.$emit('loading', false)
      }
    },
    async getList() {
      this.$emit('loading', true)
      try {
        const res = await branchDisciplineCourseList({
          disciplineGroupId: this.disciplineGroupId,
          courseName: this.queryParams.courseName,
          semesterId: this.queryParams.semesterId
        })
        if (res.code == 200) {
          this.courseList = res.data
          this.initList = res.data
        }
      } finally {
        this.$emit('loading', false)
      }
    },
    to(item) {
      this.$router.push({
        path: '/course/add',
        query: {
          type: 'detail',
          courseId: item.courseId,
          modelType: item.courseTemplate
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.coverTip {
  z-index: 3;
  top: 4px;
  left: -10px;
  width: 56px;
  height: 29px;
}

@mixin btn_plain($bg_color, $color) {
  background: $bg_color;
  color: $color;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  user-select: none;

  &:active {
    background: darken($bg_color, 5%);
    color: darken($color, 18%);
  }

  &:disabled {
    background: lighten($bg_color, 5%);
    color: lighten($color, 40%);
  }

  @content;
}

.sort {
  @include btn_plain(#ffffff, #28b28b) {
    width: 80px;
    height: 40px;
    box-sizing: border-box;
    border-radius: 8px;
    border: 1px solid #edeff0;

    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
  }
}

.content {
  height: calc(100vh - 310px + 120px);
  display: flex;
  box-sizing: border-box;
  flex-direction: column;

  .inputLine {
    height: 64px !important;
    box-sizing: border-box;
    padding: 24px 34px 0 19px;
  }

  .tip {
    font-size: 12px;
    color: rgb(255, 156, 34);
    height: 20px;
    line-height: 20px;
    margin: 2px 0 2px 19px;
  }

  .box {
    margin: 0 0 0 0;
    padding: 0 0 0 19px;
    flex: 1;
    display: flex;
    align-content: flex-start !important; /* 避免行间多余空白 */
    flex-direction: row;
    flex-wrap: wrap;
    overflow-y: auto;
  }

  .pageLine {
    padding: 0 64px 0 0;
    height: 60px;
  }

  .course {
    margin: 0 24px 41px 0;
    width: 240px;
    height: 217px;
    background: #ffffff;
    border-radius: 16px;
    border: 1px solid #ebebeb;
    box-sizing: border-box;
    padding: 12px 12px 0 12px;

    .status {
      width: 56px;
      height: 29px;
      top: 16px;
      left: -10px;
    }

    .cover {
      width: 216px;
      height: 135px;
      background: #ededed;
      border-radius: 8px;
    }

    .name {
      margin-top: 4px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 600;
      font-size: 16px;
      color: #333333;
      line-height: 22px;
      text-align: left;
      font-style: normal;
    }

    .wname {
      margin-top: 4px;
      font-family: PingFangSC, PingFang SC, sans-serif;
      font-weight: 400;
      font-size: 14px;
      color: #999999;
      line-height: 20px;
      text-align: left;
      font-style: normal;
    }
  }
}
</style>
